<template>
  <div
    class="data-statistical-container animate__faster animate__animated animate__fadeIn"
    v-loading="dataLoading"
  >
    <!-- 材料平均误差 -->
    <div class="card-view-container material-mean-error" header="材料平均误差">
      <a-empty v-if="sjylDataArr.length == 0" />
      <div class="material-error-container" v-else>
        <a-tabs>
          <a-tab-pane v-for="(item, index) in sjylDataArr" :key="index">
            <div slot="tab" class="custum-tab-name">
              <div class="nums">{{ item.value }}</div>
              <div class="tabs-name">{{ item.name }}</div>
            </div>
          </a-tab-pane>
        </a-tabs>
      </div>
    </div>
    <!-- 石油比波动 -->
    <div
      class="card-view-container chart-warp"
      :class="[item.data && 'height']"
      v-for="(item, index) in filterChartData"
      :key="index"
    >
      <div class="chart-header">
        {{ item.title ? item.title.split("@$@")[0] : "未知"
        }}<span>{{ item.title ? item.title.split("@$@")[1] : "" }}</span>
      </div>
      <div class="date-time">{{ chartDataTime }}</div>
      <div class="chart-body" :ref="'chart_dom_' + index"></div>
    </div>
  </div>
</template>

<script>
import { deepMerge } from "@/utils";
import charMixins from "@/mixins/echarts";
import themeColors from "@/theme/compileFiles/cssVaribles.less";
import themeStyles from "@/theme/compileFiles/cssVaribles.less";
import { getMaterialFluctuations } from "@/api/wisdom-beam/collect-app";
import { getField } from "@/api/common";
export default {
  mixins: [charMixins],
  data() {
    return {
      result: {},
      chartsData: [],
      chartDataTime: "",
      dataLoading: true,
      color: [
        themeColors["--echart-blue"],
        themeColors["--echart-yellow"],
        themeColors["--echart-green"],
        themeColors["--echart-light-blue"],
        themeColors["--echart-pale-red"],
        themeColors["--echart-purple"],
        themeColors["--echart-pink"],
        themeColors["--echart-orange"],
      ],
      sjylDataArr: [],
      empty: false,
      filterChartData: [],
      strengthGradeList: [],
    };
  },
  mounted() {},
  methods: {
    getAllData() {
      this.dataLoading = true;
      Promise.all([this.getFieldData(), this.getMaterialFluctuationsDatas()])
        .then((result) => {
          this.sjylDataArr = [];
          let [sjylDataArr, echartArr] = result;
          this.strengthGradeList = echartArr?.strengthGradeList || {};
          //图表
          let chartData = [];
          this.chartDataTime = echartArr.subtext;
          if (this.$parent.$data.defaultTime.length == 0) {
            this.$parent.$data.defaultTime = [
              echartArr.startTime,
              echartArr.endTime,
            ];
          }
          //一层过滤lenged
          let markLinesArr = [];
          Object.keys(echartArr).map((keys) => {
            if (keys.endsWith("Legend")) {
              let targetKey = keys.split("Legend")[0];
              let filterData = this.getSeriesByKey(targetKey, echartArr);
              chartData.push({
                key: targetKey,
                legend: echartArr[keys],
                series: filterData.data.map((v) => {
                  return {
                    type: "solid",
                    data: v,
                  };
                }),
                title: filterData.title,
              });
            }
            if (keys.endsWith("MarkLine") && echartArr[keys]) {
              markLinesArr.push({
                key: keys.split("MarkLine")[0],
                data: echartArr[keys],
              });
            }
          });
          chartData = chartData.filter((v) => v.series.length > 0);

          //平均误差
          sjylDataArr.filter((col) => {
            for (let key in echartArr) {
              if (
                col.equFieldDtu &&
                col.equFieldDtu == key &&
                echartArr[key] != 0
              ) {
                this.sjylDataArr.push({
                  equField: col.equField,
                  equFieldDtu: col.equFieldDtu,
                  value: echartArr[key],
                  name: col.equFieldName,
                });
              }
            }
          });

          //获得排序数据
          let { chartOrder } = echartArr;
          let sortData = chartOrder ? new Array(chartOrder.length) : [];
          //查询表现
          chartData.forEach((v) => {
            sortData[chartOrder.indexOf(v.key)] = v;
            let mark = markLinesArr.filter((m) => m.key == v.key)?.[0];
            let mData =
              mark &&
              mark.data.map((m) => {
                return {
                  data: m.data,
                  type: "dashed",
                  name: m.name,
                };
              });
            if (mData) {
              sortData[chartOrder.indexOf(mark.key)].series.push(...mData);
            }
          });
          this.chartsData = sortData.filter((v) => v);
          let combKeys = ["cldw", "wcbfb"];
          let combOptIndex = [];
          let filterChartData = [];
          this.chartsData.forEach((v, i) => {
            if (combKeys.includes(v.key)) {
              combOptIndex.push(i);
            }
          });
          this.chartsData.forEach((v, i) => {
            if (combKeys.includes(v.key)) {
              combOptIndex.push(i);
            }
          });
          this.chartsData.forEach((item, index) => {
            if (combKeys.includes(item.key)) {
              let minindex = Math.min.apply(null, combOptIndex);
              if (filterChartData[minindex]) {
                filterChartData[minindex].data.push(item);
              } else {
                filterChartData[minindex] = {
                  title: "单位用量",
                  data: [item],
                };
              }
            } else {
              filterChartData.push(item);
            }
          });
          this.filterChartData = filterChartData;
          this.$nextTick((_) => {
            this.filterChartData.forEach((item, index) => {
              this.initLineChar("chart_dom_" + index, item, echartArr.x);
            });
          });
        })
        .finally((_) => {
          this.dataLoading = false;
        });
    },

    filterkey(data = undefined) {
      return data ? data.key : "";
    },

    //查询字段列表
    getFieldData() {
      return new Promise((resolve, reject) => {
        let {
          conditionsData: { block },
        } = this.$parent.$data;
        getField({
          equCode: block,
        })
          .then((res) => {
            let sjylDataArr = res.data.result || [];
            resolve(sjylDataArr);
          })
          .catch((_) => {
            reject();
          });
      });
    },
    //查询材料波动图表数据
    getMaterialFluctuationsDatas() {
      return new Promise((resolve, reject) => {
        let {
          conditionsData: { block, engineerName, mixin, placePart, strength },
          defaultTime,
        } = this.$parent.$data;
        getMaterialFluctuations({
          secCode: block,
          equCode: mixin,
          startTime: defaultTime[0] || "",
          endTime: defaultTime[1] || "",
          projectName: engineerName,
          placePart: placePart,
          strengthGrade: strength,
        })
          .then((res) => {
            let { data } = res;
            let result = data.result || {};
            this.result = result;
            if (this.$parent.$data.defaultTime?.length == 0) {
              this.$parent.$data.defaultTime = [
                result.startTime,
                result.endTime,
              ];
            }
            resolve(result);
          })
          .catch((_) => {
            reject();
          });
      });
    },
    //更具key查询对应的series
    getSeriesByKey(key, data) {
      let series = [];
      Object.keys(data).map((keys, index) => {
        if (keys.startsWith(key + "Y") && data[keys]) {
          if (series.some((v) => v.key == key)) {
            series.forEach((item) => {
              if (item.key == key) {
                if (item.data) {
                  item.data.push(data[keys]);
                } else {
                  item.data = [data[keys]];
                }
              }
            });
          } else {
            series.push({
              key,
              data: data[keys],
            });
          }
        }
        if (keys == key + "Text") {
          if (series.some((v) => v.key == key)) {
            series.forEach((item) => {
              item.title = data[key + "Text"];
            });
          } else {
            series.push({
              key,
              data: [],
              title: data[key + "Text"],
            });
          }
        }

        if (keys == key + "Text") {
          if (series.some((v) => v.key == key)) {
            series.forEach((item) => {
              item.title = data[key + "Text"];
            });
          } else {
            series.push({
              key,
              data: [],
              title: data[key + "Text"],
            });
          }
        }
      });
      return series?.[0];
    },

    initLineChar(refs, opt = {}, xAxis) {
      if (Array.isArray(opt.data)) {
        this.combinationChart(refs, opt, xAxis);
        return false;
      }
      let { legend, series, key } = opt;
      let legendData = legend;
      let seriesArr = [],
        baseData = [],
        iData = [],
        index = -1;
      series.forEach((v, i) => {
        if (v.name) {
          index++;
          legendData.push(v.name);
          iData.push({
            data: v.data,
            name: v.name,
            type: "line",
            symbol: "none",
            color: this.errorColor[index],
            lineStyle: {
              type: v.type,
            },
          });
        } else {
          baseData.push({
            data: v.data,
            name: legend && legend[i],
            type: "line",
            smooth: true,
            showAllSymbol: false,
            lineStyle: {
              type: v.type,
            },
          });
        }
      });
      seriesArr = [...iData, ...baseData];
      let chart_dom = this.$refs[refs];
      let chartInstance = this.$echarts.init(chart_dom[0]);
      let llylData = [];
      Object.keys(this.result).map((key) => {
        if (key.includes("llY") && this.result[key]) {
          llylData.push(this.result[key]);
        }
      });
      let baseOptions = {
        legend: {
          data: legend || [],
        },
        color: this.color,
        grid: {
          top: "100px",
          left: "60px",
          right: "60px",
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            animation: false,
          },
          position: function (point, params, dom, rect, size) {
            var x = 0; // x坐标位置
            var y = 0; // y坐标位置
            // 当前鼠标位置
            var pointX = point?.[0];
            var pointY = point?.[1];
            // 提示框大小
            var boxWidth = size.contentSize?.[0];
            var boxHeight = size.contentSize?.[1];

            // boxWidth > pointX 说明鼠标左边放不下提示框
            if (boxWidth > pointX) {
              x = pointX + 10;
            } else {
              // 左边放的下
              x = pointX - boxWidth;
            }

            // boxHeight > pointY 说明鼠标上边放不下提示框
            if (boxHeight > pointY) {
              y = 5;
            } else {
              // 上边放得下
              y = pointY - boxHeight - 30;
            }
            return [x, y];
          },
          formatter: (params) => {
            let htmlStr = "";
            //单独处理材料用量
            //placePartList
            //浇筑部位
            let placePartList = this.result?.placePartList || [];
            if (key == "clyl") {
              let bodyHtmlStr = "";
              params.forEach((item) => {
                bodyHtmlStr += `<div class="data-row">
                                <div>${item.marker}${item.seriesName}</div>
                                <div>${item.value}</div>
                                <div>${
                                  llylData?.[item.seriesIndex]?.[
                                    item.dataIndex
                                  ] + "" || "--"
                                }</div>
                              </div>`;
              });
              return `<div class="gksys-clbd-custom-tooltip-container">
                        <div class="axis-value">时间：${
                          params[0].axisValue
                        }</div>
                        <div class="ratio-name">标号：${
                          this.strengthGradeList[params[0].dataIndex] || "--"
                        }</div>
                        <div class="ratio-name">浇筑部位：${
                          placePartList?.[params[0].dataIndex] || "--"
                        }</div>
                        <div class="custom-tooltip-body">
                            <div class="tooltip-header">
                                <div>材料</div>
                                <div>实际用量</div>
                                <div>理论用量</div>
                            </div>
                            ${bodyHtmlStr}
                        </div>
                   </div>`;
            } else {
              params.forEach((v) => {
                htmlStr += `<div class="data-item">
                            <div>${v.marker}</div>
                            <div class="name">${v.seriesName}</div>
                            <div class="value">${v.data}</div>
                        </div>`;
              });
              return `<div class="common-tooltip-container">
                        <div class="tooltip-title">时间：${
                          params[0].axisValue
                        }</div>
                        <div class="ratio-name">标号：${
                          this.strengthGradeList[params[0].dataIndex] || "--"
                        }</div>
                        ${htmlStr}
                    </div>`;
            }
          },
        },
        xAxis: {
          type: "category",
          data: xAxis,
        },
        series: seriesArr,
      };
      chartInstance.setOption(
        deepMerge(this.lineChartsOptions, baseOptions),
        true
      );
      //开启响应式
      window.addEventListener("resize", () => {
        chartInstance.resize();
      });
    },

    //组合图例
    combinationChart(refs, opt = {}, xAxis) {
      let { data } = opt;
      let seriesArr = [];
      let chart_dom = this.$refs[refs];
      let chartInstance = this.$echarts.init(chart_dom[0]);
      data.forEach((v, index) => {
        v.series.forEach((item, idx) => {
          seriesArr.push({
            data: item.data,
            name: v?.legend?.[idx],
            type: "line",
            smooth: true,
            showAllSymbol: false,
            xAxisIndex: index,
            yAxisIndex: index,
            lineStyle: {
              type: item.type,
            },
          });
        });
      });
      let baseOptions = {
        legend: {
          data: data?.[0]?.legend || [],
          icon: "rect",
          itemHeight: 14,
          itemWidth: 19,
          itemGap: 20,
          right: 40,
          top: 56,
          textStyle: {
            color: "#525A5D",
            fontSize: 14,
          },
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            animation: false,
          },
          position: function (point, params, dom, rect, size) {
            var x = 0; // x坐标位置
            var y = 0; // y坐标位置
            // 当前鼠标位置
            var pointX = point?.[0];
            var pointY = point?.[1];
            // 提示框大小
            var boxWidth = size.contentSize?.[0];
            var boxHeight = size.contentSize?.[1];

            // boxWidth > pointX 说明鼠标左边放不下提示框
            if (boxWidth > pointX) {
              x = pointX + 10;
            } else {
              // 左边放的下
              x = pointX - boxWidth;
            }

            // boxHeight > pointY 说明鼠标上边放不下提示框
            if (boxHeight > pointY) {
              y = 5;
            } else {
              // 上边放得下
              y = pointY - boxHeight - 30;
            }
            return [x, y];
          },
          formatter: (params) => {
            let llylData = [];
            Object.keys(this.result).map((key) => {
              if (key.includes("cldwLlY") && this.result[key]) {
                llylData.push(this.result[key]);
              }
            });
            let splitData = [[], []];
            params.forEach((v) => {
              if (v.axisId.includes("1")) {
                splitData[1].push(v);
              } else {
                splitData?.[0].push(v);
              }
            });
            let { axisValue, dataIndex } = params?.[0];
            let bodyHtmlStr = "";
            splitData?.[0].forEach((item, index) => {
              bodyHtmlStr += `<div class="data-row">
                                    <div>${item.marker}${item.seriesName}</div>
                                    <div>${item.value}</div>
                                    <div>${
                                      llylData?.[item.seriesIndex]?.[
                                        item.dataIndex
                                      ] + "" || "--"
                                    }</div>
                                    <div>${splitData[1]?.[index]?.value}</div>
                               </div>`;
            });
            return `<div class="gksys-clbd-custom-tooltip-container">
                        <div class="axis-value">时间：${axisValue}</div>
                        <div class="ratio-name">标号：${
                          this.strengthGradeList[dataIndex] || "--"
                        }</div>
                        <div class="custom-tooltip-body">
                            <div class="tooltip-header">
                                <div>材料</div>
                                <div>单位用量</div>
                                <div>理论用量</div>
                                <div>误差</div>
                            </div>
                            ${bodyHtmlStr}
                        </div>
                   </div>`;
          },
        },
        axisPointer: {
          link: { xAxisIndex: "all" },
        },
        grid: [
          {
            top: 130,
            left: 115,
            right: 70,
            height: 260,
          },
          {
            left: 115,
            right: 70,
            top: 450,
            height: 260,
          },
        ],
        xAxis: [
          {
            gridIndex: 0,
            type: "category",
            boundaryGap: false,
            data: xAxis,
            axisLine: {
              onZero: false,
            },
            axisLabel: {
              color: themeStyles["--echart-text-color"],
              fontSize: "14",
              margin: 25,
            },
            axisTick: {
              length: 10,
              alignWithLabel: true,
            },
          },
          {
            gridIndex: 1,
            type: "category",
            boundaryGap: false,
            axisLabel: {
              show: true,
              color: "rgba(0, 0, 0, 0)",
              fontSize: "14",
              margin: 0,
            },
            axisLine: {
              onZero: false,
            },
            axisTick: {
              length: 10,
              alignWithLabel: true,
            },
            data: xAxis,
            position: "top",
          },
        ],
        yAxis: [
          {
            gridIndex: 0,
            name:
              "{name|" +
              data?.[0]?.title.split("@$@")?.[0] +
              "}{unit|" +
              data?.[0]?.title.split("@$@")?.[1] +
              "}",
            type: "value",
            nameTextStyle: {
              rich: {
                name: {
                  fontSize: 14,
                  color: "#333",
                },
                unit: {
                  fontSize: 12,
                  padding: [0, 0, 0, 10],
                  color: "#999",
                },
              },
            },
          },
          {
            name:
              "{name|" +
              data[1]?.title.split("@$@")?.[0] +
              "}{unit|" +
              data[1]?.title.split("@$@")?.[1] +
              "}",
            gridIndex: 1,
            type: "value",
            inverse: true,
            nameTextStyle: {
              rich: {
                name: {
                  fontSize: 14,
                  color: "#333",
                  padding: [0, 0, 0, 25],
                },
                unit: {
                  fontSize: 12,
                  padding: [0, 0, 0, 10],
                  color: "#999",
                },
              },
            },
          },
        ],
        series: seriesArr,
      };
      chartInstance.setOption(baseOptions, true);
      //开启响应式
      window.addEventListener("resize", () => {
        chartInstance.resize();
      });
    },
  },
};
</script>

<style lang="less" scoped>
.data-statistical-container {
  width: 100%;
  height: 100%;
  padding-right: 10px;
  /deep/.common-tooltip-container {
    .tooltip-title {
      margin-bottom: 6px;
    }
    .ratio-name {
      margin-bottom: 6px;
    }
    .data-item {
      display: flex;
      margin-bottom: 6px;
      &:last-child {
        margin: 0;
      }
      .name {
        margin-left: 4px;
      }
      .value {
        font-weight: bold;
        margin-left: auto;
      }
    }
  }
  /deep/.gksys-clbd-custom-tooltip-container {
    .axis-value {
      font-size: 14px;
      color: #333;
    }
    .ratio-name {
      margin: 10px 0;
    }
    .custom-tooltip-body {
      display: flex;
      flex-direction: column;
      .tooltip-header {
        height: 40px;
        line-height: 40px;
        font-size: 14px;
        background: #f2f4f5;
        display: flex;
        div {
          width: 120px;
          text-align: center;
          color: #000;
        }
      }
      .data-row {
        height: 40px;
        line-height: 40px;
        display: flex;
        border-bottom: 1px solid #d9d9d9;
        div {
          width: 120px;
          text-align: center;
          position: relative;
          &:first-child {
            span {
              position: absolute;
              top: 50%;
              left: 20px;
              transform: translateY(-50%);
            }
          }
        }
      }
    }
  }
  .custom-scrollbar();
  //材料平均误差
  .material-mean-error {
    background: #fff;
    padding: 20px 0;
    &::before {
      margin: 0 20px;
    }
    .box-shadow();
    .material-error-container {
      .flex();
      padding-top: 30px;
      /deep/.ant-tabs {
        .ant-tabs-ink-bar {
          display: none !important;
        }
        .ant-tabs-bar {
          border: none !important;
          margin: 0;
        }
        .ant-tabs-tab {
          margin: 0;
          width: 200px;
          text-align: center;
          padding: 0;
          height: 90px;
          color: var(--primary-color) !important;
          cursor: default;
          .custum-tab-name {
            height: 100%;
            .flex();
            flex-direction: column;
            align-items: center;
            justify-content: center;
            .nums {
              color: var(--primary-color);
              padding-bottom: 10px;
              font-weight: bold;
              font-size: 36px;
            }
            .tabs-name {
              color: #999;
              font-size: 14px;
            }
          }
          &::before {
            display: none;
          }
          position: relative;
          &::after {
            content: "";
            position: absolute;
            width: 2px;
            height: 36px;
            background: #ededed;
            top: 50%;
            transform: translateY(-50%);
            right: 0;
          }
          &:last-child {
            &::after {
              display: none;
            }
          }
        }
      }
    }
  }
  .card-view-container {
    width: 100%;
    &:last-child {
      margin: 0;
    }
    &.chart-warp {
      height: 380px;
      position: relative;
    }
    &.height {
      height: 760px;
      .date-time {
        padding-top: 20px;
      }
    }
    .chart-header {
      font-size: 16px;
      height: 18px;
      padding-left: 10px;
      color: #525a5d;
      display: flex;
      align-items: center;
      > span {
        font-size: 14px;
        color: #999;
        margin-left: 10px;
      }
    }
    .date-time {
      font-size: 14px;
      color: #999;
      padding-top: 30px;
      padding-left: 12px;
    }
    .chart-body {
      position: absolute;
      width: 100%;
      height: 100%;
      top: 0;
      left: 0;
    }
  }
}
</style>
